﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


namespace Pufang.Execl.BusinessCompute.XMLUtilities
{
    public static class Json
    {
        /// <summary>
        /// 把对象序列化成对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static String Serialize(Object obj)
        {
            string outPut=JsonConvert.SerializeObject(obj);

            return outPut;
        }

        /// <summary>
        /// 把字符串反序列化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="outPutObject"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string outPutObject)
        {
            T t = default(T);
            Object obj = JsonConvert.DeserializeObject<T>(outPutObject);
            t = (T)obj;

            return t;
        }
    }

    public static class Formatter
    {

        public static byte[] Serialize(Object obj)
        {
            MemoryStream stream = new MemoryStream();
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                formatter.Serialize(stream, obj);
                byte[] date = null;
                date = stream.ToArray();
                stream.Close();
                return date;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// 把字节反序列化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="outPutObject"></param>
        /// <returns></returns>
        public static T Deserialize<T>(byte[] date)
        {
            T t = default(T);
            if (date == null || date.Length <= 0) return default(T);
            MemoryStream stream = new MemoryStream(date);
            BinaryFormatter formatter = new BinaryFormatter();

            Object obj = formatter.Deserialize(stream);
            t = (T)obj;
 
            return t;
        }
    }
}
